<script setup lang="ts">
import { PropType, ref, reactive } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Descriptions } from '@/components/Descriptions'
import { Table } from '@/components/Table'
import { spFeedSeeApi } from '@/api/sp/feed'
import { spFeedSeeExcelApi } from '@/api/forms'
// import { useTable } from '@/hooks/web/useTableTest'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useCache } from '@/hooks/web/useCache'
import Assets from './Assets.vue'
import { ElCard } from 'element-plus'
import { useDesign } from '@/hooks/web/useDesign'

const { getPrefixCls } = useDesign()

const prefixCls = getPrefixCls('content-wrap')

const data = ref<any>({})
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const actionType = ref('')
const props = defineProps({
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  },
  id: {
    type: String,
    default: null
  }
})
// const spFeedAssetList = async (val) => {
//   val.feed_id = props.id
//   return spFeedAssetListApi(val)
// }
// const { register, tableObject, methods } = useTable<
//   {
//     total: number
//     list: any[]
//   },
//   any
// >({
//   getListApi: spFeedAssetList,
//   response: {
//     data: 'data',
//     count: 'count'
//   }
// })

// const { getList } = methods

// getList()
// 调用查看接口获取信息
const getSee = async () => {
  const res = await spFeedSeeApi({ id: props.id })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    data.value = res.data
  }
}
const feed_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 20
  },
  {
    field: 'forage_name',
    label: '名称',
    width: 90
  },
  {
    field: 'ratio',
    label: '比例（%）'
  },
  {
    field: 'weight',
    label: '总喂养重量',
    width: 180
  }
])

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'asset_code',
    label: '注射编号',
    width: 200
  },
  {
    field: 'asset_code_2',
    label: '项圈编号',
    width: 200
  },
  {
    field: 'earcon_code',
    width: 200,
    label: '耳标编码'
  },
  {
    field: 'breed',
    label: '畜别',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed', cellValue)
    },
    width: 100
  },
  {
    field: 'breed_sub',
    width: 200,
    label: '品种',
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('breed_sub', cellValue)
    }
  }
])
const { allSchemas } = useCrudSchemas(crudSchemas)
const enclosure_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'name',
    label: '栏位'
  },
  {
    field: 'this_asset_count',
    label: '存栏数',
    width: 150
  },
  {
    field: 'all_weight',
    label: '栏位总重量（公斤）',
    width: 200
  }
])

const action = async (type: string) => {
  actionType.value = type
  switch (type) {
    case 'assets':
      dialogTitle.value = '喂养资产'
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}
const init = async () => {
  await getSee()
}
init()
const exportClick = async () => {
  let { data }: any = await spFeedSeeExcelApi({
    request: {
      id: props.id,
      // my_org_id: ''
      my_org_id: wsCache.get('userInfo').default_org_id
    },
    layout_data: {
      file_name: '喂养单饲料详情',
      column_cell_start: 'A6',
      column_value: 'detailed',
      column_data: [
        {
          title: '序号',
          width: 5,
          cell_type: 'key'
        },
        {
          title: '饲料名称',
          width: 80,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'forage_name'
        },
        {
          title: '饲料总数量',
          width: 30,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'weight'
        },
        {
          title: '比例',
          width: 30,
          cell_type: 'string',
          give_type: 'variable',
          give_value: 'ratio'
        }
      ],
      custom: [
        {
          cell_type: 'string',
          cell: 'A1:D1',
          give_type: 'format',
          give_value: '喂养单饲料详情',
          horizontal: 'center',
          border: true,
          size: '16'
        },
        {
          cell_type: 'string',
          cell: 'A2:B2',
          give_type: 'format',
          give_value: '牧场名称：${pasture_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'C2:D2',
          give_type: 'format',
          give_value: '单号：${code}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A3:B3',
          give_type: 'format',
          give_value: '类型：${dict.feed_type.${type}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'C3:D3',
          give_type: 'format',
          give_value: '状态：${dict.feed_state.${state}}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A4:B4',
          give_type: 'format',
          give_value: '喂养配方：${forage_formula_name}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'C4:D4',
          give_type: 'format',
          give_value: '喂养时间：${feed_time}',
          horizontal: 'left',
          border: true,
          size: '12'
        },
        {
          cell_type: 'string',
          cell: 'A5:D5',
          give_type: 'template',
          give_value: '喂养栏位：{% for k,v in enclosureData %}{{ v.name }} {% endfor %}',
          horizontal: 'left',
          border: true,
          size: '12'
        }
      ],
      dict: ['feed_type', 'feed_state']
    }
  })
    .catch(() => {})
    .finally(() => {
      // saveLoading.value = false
    })
  if (data) {
    window.open(data.url)
  }
}
</script>

<template>
  <div class="mb-10px w-[100%] flex justify-end">
    <ElButton type="primary" @click="exportClick()"> 导出EXCEL </ElButton>
  </div>
  <ContentWrap title="主数据">
    <Descriptions :schema="props.detailSchema" :data="data">
      <template #type="{ row }">
        <div>{{ getDictLabel('feed_type', row.type) }}</div>
      </template>
      <template #state="{ row }">
        <div>{{ getDictLabel('feed_state', row.state) }}</div>
      </template>
    </Descriptions>
  </ContentWrap>

  <ElCard :class="[prefixCls, 'mb-20px']" shadow="never">
    <template #header>
      <div class="flex items-center justify-between">
        <span class="text-16px font-700">喂养栏位</span>
        <el-button class="button" text @click="action('assets')">查看资产</el-button>
      </div>
    </template>
    <div>
      <slot>
        <Table
          :columns="enclosure_columns"
          :data="data.enclosureData"
          :selection="false"
          :border="true"
        />
      </slot>
    </div>
  </ElCard>
  <ContentWrap title="饲料配方明细">
    <Table :columns="feed_columns" :data="data.detailed" :selection="false" :border="true" />
  </ContentWrap>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Assets v-if="actionType == 'assets'" :detail-schema="allSchemas.detailSchema" :id="props.id" />
    <template #footer>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
